import { createAlova } from 'alova';
import VueHook from 'alova/vue';
import adapterFetch from 'alova/fetch';
import { useAuthStore } from '@/stores/auth';


const alovaInstance = createAlova({
  statesHook: VueHook,
  requestAdapter: adapterFetch(),
  baseURL: 'http://127.0.0.1:8081/api',
  beforeRequest(method) {
    const userStore = useAuthStore();
    const token = userStore.token;
    if (token) {
      method.config.headers.Authorization = `Bearer ${token}`;
    }
  },
  responded: {
    onSuccess: async (response) => {
     
      const data = await response.json();
      
      if (response.status === 1) {
        // token无效时跳转登录页
        const authStore = useAuthStore();
        authStore.clearAuth();
        window.location.href = '/login';
      }
      return data; // 返回解析后的数据
    },
    onError: (err) => {
      throw err;
    }
  }
});

export const loginAPI = (data) => 
  alovaInstance.Post('/login', data);

export const getUsers = () => 
  alovaInstance.Get('/users');